package com.owen.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUtil {

	/**
	 * 文件上传（将InputStream输入流写入到本地磁盘“up”）
	 * @param is
	 * @param uploadFilePath
	 * @throws Exception
	 */
	public static String uploadFile(InputStream is, String uploadFilePath) throws Exception {
		if (is != null && StrUtil.isNotEmpty(uploadFilePath)) {
			Path uploadDirectory = Paths.get(uploadFilePath).getParent();
			// 文件夹不存在则先创建文件夹
			if (!Files.isDirectory(uploadDirectory)) {
				Files.createDirectories(uploadDirectory);
			}
			OutputStream os = Files.newOutputStream(Paths.get(uploadFilePath));
			IoUtil.copy(is, os);
			is.close();
			os.close();
		}
		return uploadFilePath;
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
}
